package mvc;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import java.net.*;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.util.*;
import org.apache.commons.fileupload.disk.*;

public class Servl extends HttpServlet{

	private String username;
	private HttpSession session;
	DBconn db;	

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			 this.doPost(req, resp);  
}

public void init() throws ServletException{
   	try {   		
		db = new DBconn();
		db.connect();
   	} catch (IOException e) {}
}

public void destroy(){
	db.closeConnection();
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = response.getWriter();

try {

Cookie autocook;
String autousername = null;
String autopassword = null;

session = request.getSession(true);

// No user in session, but maybe in cookie?
if(session.getAttribute("user")==null){
	
	// Decoder for auto login cookies
	BASE64Decoder dec = new BASE64Decoder();
	
	// Get the cookie values    	
	autousername = new String(dec.decodeBuffer(CookieUtilities.getCookieValue(request, "mayclub.username", "")));
	autopassword = new String(dec.decodeBuffer(CookieUtilities.getCookieValue(request, "mayclub.password", "")));
	

	if (db.sqlQuery("SELECT username, firstname, lastname, isadmin from person where username = '"+autousername+"' and password = MD5('"+autopassword+"')").next()) {

		String u = db.getString("username");
		String fn = db.getString("firstname");
		String ln = db.getString("lastname");
		String ia = db.getString("isadmin");
		Boolean isadmin = false;
		username = u;
		
		if(ia.equals("1"))
			isadmin = true;

		//Create user
		User user = new User(u,fn,ln,isadmin);

		// Save user in session
		session.setAttribute("user", user);
		request.setAttribute("errorMessage", "AUTOLOGIN YEAH");
		}	
	else{		
		// User not found in cookies. Create a "empty" user
		session.setAttribute("user",new User("","","",false));		
	}	}
else{
		User user = (User) session.getAttribute("user");
		username = user.getUsername();
}

//  -- LOGOUT --
if(request.getParameter("state")!= null && request.getParameter("state").equals("logout")){

		session.invalidate();
		
		
		Cookie us = CookieUtilities.getCookie(request, "mayclub.username");
		Cookie pw = CookieUtilities.getCookie(request, "mayclub.password");		
		
		us.setMaxAge(0);
		pw.setMaxAge(0);
		
		response.addCookie(us);
		response.addCookie(pw);
		
		
		request.setAttribute("errorMessage", "You have been logged out");
		RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/login.jsp");
		disp.forward(request, response);
		return;

}

//  -- ADD USER --
else if(request.getParameter("state")!= null && request.getParameter("state").equals("adduser")){

		if(request.getParameter("addusername")!=null){
		// Get the data from add user form	
		String addusername = request.getParameter("addusername");
		String addfirstname = request.getParameter("addfirstname");
		String addlastname = request.getParameter("addlastname");
		String addemail = request.getParameter("addemail");
		String addisadmin = request.getParameter("addisadmin");	
	
		if(addisadmin!=null)
			addisadmin = "1";
				
		String errorMessage = "";
		boolean error = false;


		if(addusername.equals("") || db.sqlQuery("select username from person where username ='"+addusername+"'").next()){
			errorMessage = (String)request.getAttribute("errorMessage");
			if(errorMessage==null)
				errorMessage="";
			request.setAttribute("errorMessage",errorMessage + "Username error: <b>"+addusername+"</b><br>");
			error = true;
		}
		if(addfirstname.equals("")){
			errorMessage = (String)request.getAttribute("errorMessage");
			if(errorMessage==null)
				errorMessage="";
			request.setAttribute("errorMessage",errorMessage + "Firstname error<br>");
			error = true;
		}
		if(addlastname.equals("")){
			errorMessage = (String)request.getAttribute("errorMessage");
			if(errorMessage==null)
				errorMessage="";
			request.setAttribute("errorMessage",errorMessage + "Lastname error<br>");
			error = true;
		}
		if(addemail.equals("")){
			errorMessage = (String)request.getAttribute("errorMessage");
			if(errorMessage==null)
				errorMessage="";
			request.setAttribute("errorMessage",errorMessage + "Email error<br>");
			error = true;
		}
		
		if(error){
		RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/adduser.jsp");
		disp.forward(request, response);
		return;}
		
		db.sqlUpdate("INSERT INTO person VALUES('"+addusername+"','"+addfirstname+"','"+addlastname+"','"+addemail+"',MD5('"+addusername+"'),'"+addisadmin+"')");
		request.setAttribute("errorMessage","User <b>"+addusername+"</b> has been added");
		RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/adduser.jsp");
		disp.forward(request, response);
		return;	
	} else {
		RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/adduser.jsp");
		disp.forward(request, response);
		return;}
}

//  -- ADD NEWS --
else if(request.getParameter("state")!= null && request.getParameter("state").equals("addnews")){

		if(request.getParameter("up")!=null){
		
		db.sqlUpdate("INSERT INTO news(person, topic, news_text) values('"+username+"','"+request.getParameter("news_topic")+"','"+request.getParameter("news_text")+"')");		

		request.setAttribute("errorMessage","News post added");
		
		RequestDispatcher disp =getServletContext().getRequestDispatcher("/servlet/mvc.Servl?state=news");
		disp.forward(request, response);
		return;	
		} 
		else {
			RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/addnews.jsp");
			disp.forward(request, response);
		return;
		}
}

// -- LOGIN --
else if(request.getParameter("state")!= null && request.getParameter("state").equals("login")){
	
	// Check if request has the username param. If not, direct to login.jsp
	if(request.getParameter("loginusername")==null){
		request.setAttribute("errorMessage", "You have to login thru this page");
		RequestDispatcher disp = getServletContext().getRequestDispatcher("/mvcjsp/login.jsp");
		disp.forward(request, response);
		return;}

	// Get the username and password from the login form	
	String loginusername = request.getParameter("loginusername");
	String loginpassword = request.getParameter("loginpassword");
	
	// If username not specified, direct to login.jsp   
	if (loginusername.equals("")) {
		request.setAttribute("errorMessage", "User name not specified");
		RequestDispatcher disp = getServletContext().getRequestDispatcher("/mvcjsp/login.jsp");
		disp.forward(request, response);
		return;}

	// Check if username is not in the db, direct to login.jsp
	if(!db.sqlQuery("SELECT username from person where username = '"+loginusername+"'").next()){	
		request.setAttribute("errorMessage", "User not found");
		RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/login.jsp");
		disp.forward(request, response);
		return;}

	// Check if password is correct and 
	// get firstname, lastname, isadmin to put in the user-session
	if (db.sqlQuery("SELECT username, firstname, lastname, isadmin from person where username = '"+loginusername+"' and password = MD5('"+loginpassword+"')").next()) {

		String u = db.getString("username");
		String fn = db.getString("firstname");
		String ln = db.getString("lastname");
		String ia = db.getString("isadmin");
		Boolean isadmin = false;
		username = u;
		
		if(ia.equals("1"))
			isadmin = true;

		// create a session
		session = request.getSession(true);

		//Create user
		User user = new User(u,fn,ln,isadmin);

		// Save user in session
		session.setAttribute("user", user);
		
		
		// Encoder for cookies
		BASE64Encoder enc = new BASE64Encoder();

		// Cookies for keeping user logged in
		// Store username 1 week		
		Cookie cook = new Cookie("mayclub.username", enc.encode(loginusername.getBytes()));
		cook.setMaxAge(3600*24*7);
		response.addCookie(cook);
		
		// Store password 1 week
		cook = new Cookie("mayclub.password", enc.encode(loginpassword.getBytes()));   
		cook.setMaxAge(3600*24*7);         
		response.addCookie(cook);
		
		// Get redirect page
		
		db.sqlQuery("select redirect from profile where person = '"+username+"'").next();

		// Direct to the page user has chosen
		RequestDispatcher disp = getServletContext().getRequestDispatcher("/servlet/mvc.Servl?state="+db.getString("redirect"));
		disp.forward(request, response);
		return;
		}

		// The username stays in the login form
		request.setAttribute("loginusername",loginusername);
		request.setAttribute("x21",loginusername);
	
		// Error message, wrong password
		request.setAttribute("errorMessage", "Wrong password");
		RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/login.jsp");
		disp.forward(request, response);
		return;
}
 	
//  -- GUESTBOOK --
else if(request.getParameter("state")!= null && request.getParameter("state").equals("guestbook")){
	
	// remove
	if(request.getParameter("remove")!= null){
	db.sqlUpdate("delete from gb where (gb_id ='"+ request.getParameter("remove") +"' and person = '"+ username +"')"+
				"or (gb_id ='"+ request.getParameter("remove") +"' and '" + username + "' = "+
				"(select username from person where username ='" +username + "' and isadmin = 1))");}

	if(request.getParameter("update")!= null && request.getParameter("textarea") != null){
	
	// Check textarea
	if(request.getParameter("textarea").equals("")){
		request.setAttribute("errorMessage", "Error, nothing to post!");}
		
	// Insert into gb and logger
	else{db.sqlUpdate("INSERT INTO gb(person, gb_text) values('"+username+"','"+ request.getParameter("textarea").replaceAll("'","\\\\'") +"')");}
	}

	// Wich page is shown?
	int pageCount = 1;
	// Check if user wants to show another page
	if(request.getParameter("page")!= null){
		pageCount = Integer.parseInt(request.getParameter("page"));
		if(pageCount<1)
			pageCount=1;
	}
	
	int nr;

	db.sqlQuery("select nrgb from profile where person = '"+username+"'").next();
    nr = Integer.parseInt(db.getString("nrgb"));

	// Create the guestbook
	Guestbook gb = new Guestbook(db,pageCount,nr);

	// Get session and put the guestbook in it
	session = request.getSession(false);
	session.setAttribute("gb", gb);

	// Forward
	RequestDispatcher disp = getServletContext().getRequestDispatcher("/mvcjsp/guestbook.jsp");
	disp.forward(request, response);
	return;
}

//  -- NEWS --
else if(request.getParameter("state")!= null && request.getParameter("state").equals("news")){

	if(request.getParameter("remove")!= null){
	db.sqlUpdate("delete from news where (news_id ='"+ request.getParameter("remove") +"' and person = '"+ username +"')"+
				"or (news_id ='"+ request.getParameter("remove") +"' and '" + username + "' = "+
				"(select username from person where username ='" +username + "' and isadmin = 1))");}



	if(request.getParameter("fullnews")!= null){
		FullNews fullnews = new FullNews(db,request.getParameter("fullnews"));
		session = request.getSession(true);
		session.setAttribute("fullnews", fullnews);
		RequestDispatcher disp = getServletContext().getRequestDispatcher("/mvcjsp/fullnews.jsp");
		disp.forward(request, response);
		return;
	} 	
			
	// Wich page is shown?
	int pageCount = 1;
	// Check if user wants to show another page
	if(request.getParameter("page")!= null){
		pageCount = Integer.parseInt(request.getParameter("page"));
		if(pageCount<1)
			pageCount=1;
	}

	// Create the newspage
	News news = new News(db,pageCount);

	// Get session and put the newspage in it
	session = request.getSession(true);		
	session.setAttribute("news", news);
	
	// Forward
	RequestDispatcher disp = getServletContext().getRequestDispatcher("/mvcjsp/news.jsp");
	disp.forward(request, response);
	return;
}

//  -- UPLOAD PHOTO --
else if(request.getParameter("state")!= null && request.getParameter("state").equals("upload")){

	if(ServletFileUpload.isMultipartContent(request)){		
		try{
		DiskFileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload upload=new ServletFileUpload(factory);

		// If file size exceeds, a FileUploadException will be thrown
		//fu.setSizeMax(1000000);

		List fileItems = upload.parseRequest(request);	
		Iterator iter = fileItems.iterator();
		FileItem fi;
		
		while (iter.hasNext()) {
			fi = (FileItem) iter.next();
				
			if(!fi.isFormField()){
				
				String fileName = fi.getName();
				User user = (User) session.getAttribute("user");
				
				fi.write(new File("/Library/Tomcat/Home/webapps/ROOT/mvcjsp/photos/"+user.getUsername()+".jpg"));
				db.sqlUpdate("update profile set hasphoto = 1 where person = '"+user.getUsername()+"'");
				request.setAttribute("errorMessage", "Photo succesfully uploaded!");
			}
		}
		} 
		catch (Exception e) {		
		e.getStackTrace();
		} 
		
	}
		RequestDispatcher disp = getServletContext().getRequestDispatcher("/mvcjsp/upload.jsp");
		disp.forward(request, response);
		return;

}

//  -- PROFILE --
else if(request.getParameter("state")!= null && request.getParameter("state").equals("profile")){

	// Wich page is shown?
	String stringProfile = "robert";

	// Check if user wants to show another page
	if(request.getParameter("myprofile")!= null)
	{
		User user = (User) session.getAttribute("user");
		stringProfile = user.getUsername();
		
	} else if(request.getParameter("profile")!= null)
		stringProfile = request.getParameter("profile");

	// Create the profile
	Profile profile = new Profile(db,stringProfile);

	// Put the profile in the session	
	session.setAttribute("profile", profile);

	// Forward
	RequestDispatcher disp = getServletContext().getRequestDispatcher("/mvcjsp/profile.jsp");
	disp.forward(request, response);
	return;
}

//  -- EDIT PROFILE --
else if(request.getParameter("state")!= null && request.getParameter("state").equals("edit")){
	
	 String stringProfile = "tomas";

	        if(request.getParameter("edit") != null && request.getParameter("edit").equals("up")){

	                db.sqlUpdate("update person set firstname = '"+request.getParameter("firstname")+"' where username = '"+username+"'");
	                db.sqlUpdate("update person set lastname = '"+request.getParameter("lastname")+"' where username = '"+username+"'");
	                db.sqlUpdate("update person set email = '"+request.getParameter("email")+"' where username = '"+username+"'");
	                db.sqlUpdate("update profile set website = '"+request.getParameter("website")+"' where person = '"+username+"'");
	                db.sqlUpdate("update profile set mobilenr = '"+request.getParameter("mobilenr")+"' where person = '"+username+"'");
	                db.sqlUpdate("update profile set profile_text ='"+request.getParameter("profile_text")+"' where person ='"+username+"'");

	                request.setAttribute("errorMessage", "Profile Updated!");

	        }
	        if(request.getParameter("edit") != null && request.getParameter("edit").equals("up2")){

	                db.sqlUpdate("update profile set nrgb = '"+request.getParameter("nrgb")+"' where person = '"+username+"'");
	                db.sqlUpdate("update profile set redirect = '"+request.getParameter("redirect")+"' where person = '"+username+"'");

	                request.setAttribute("errorMessage", "Site costumized!");

	        }

	        User user = (User) session.getAttribute("user");
	        stringProfile = user.getUsername();
	        Profile profile = new Profile(db,stringProfile);
	        session.setAttribute("profile", profile);

	        RequestDispatcher disp = getServletContext().getRequestDispatcher("/mvcjsp/editprofile.jsp");
	        disp.forward(request, response);
	        return;
	}
	

//  -- SEARCH --
else if(request.getParameter("state")!= null && request.getParameter("state").equals("search")){

	if(request.getParameter("sUser") == null){
		request.setAttribute("errorMessage", "Search again");
		RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/search.jsp");
		disp.forward(request, response);
		return;}		
	
	if(request.getParameter("sUser").length() < 2){
		request.setAttribute("errorMessage", "2 chars at lest");
		RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/search.jsp");
		disp.forward(request, response);
		return;}
	
	else{
	Search search = new Search(db,request.getParameter("sUser"));
	session.setAttribute("search",search);
	RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/search.jsp");
	disp.forward(request, response);
	return;

}
}

//  -- Something wrong --
else {
	request.setAttribute("errorMessage","Can only access through valid links");
	RequestDispatcher disp =getServletContext().getRequestDispatcher("/mvcjsp/login.jsp");
	disp.forward(request, response);
	return;	}

} catch (SQLException e) {out.println(e);}

}
}
